<template>
  <div class="add-chapter">
    <div class="title">{{ isEdit ? '编辑章节' : '新增章节' }}</div>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="章节标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入章节标题" />
      </el-form-item>
    </el-form>
    <div class="button-group">
      <el-button type="primary" @click="handleSubmit">确定</el-button>
      <el-button v-if="isEdit" type="danger" @click="handleDelete">删除</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addChapterData, editChapter, delChapterInfo } from '@/api/bykt/chapter'

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false
  },
  courseId: {
    type: [String, Number],
    required: true
  },
  chapterData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['refresh', 'cancel'])

const formRef = ref(null)
const form = reactive({
  title: '',
  courseId: props.courseId,
  sort: 1, // 添加排序字段
  id: undefined // 明确初始化id字段
})

const rules = {
  title: [{ required: true, message: '请输入章节标题', trigger: 'blur' }]
}

// 监听编辑数据变化
watch(() => props.chapterData, (newVal) => {
  console.log('章节数据变化:', newVal)
  if (props.isEdit && newVal) {
    // 移除对newVal.title的检查，只要有数据就设置
    form.title = newVal.title || ''
    form.id = newVal.id
    form.courseId = newVal.courseId || props.courseId // 优先使用数据中的courseId
    form.sort = newVal.sort || 1 // 添加排序字段
  } else if (!props.isEdit) {
    // 新增模式下清空表单
    form.title = ''
    form.id = undefined
    form.courseId = props.courseId
    form.sort = 1
  }
}, { deep: true, immediate: true })

// 额外监听courseId变化
watch(() => props.courseId, (newVal) => {
  if (newVal) {
    form.courseId = newVal
  }
}, { immediate: true })

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  try {
    if (props.isEdit) {
      await editChapter(form)
      ElMessage.success('编辑成功')
      emit('refresh')
    } else {
      await addChapterData(form)
      ElMessage.success('添加成功')
      emit('refresh')
    }
  } catch (error) {
    console.error('操作失败：', error)
    ElMessage.error('操作失败')
  }
}

// 删除章节
const handleDelete = () => {
  ElMessageBox.confirm('确认删除该章节及其所有视频吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      console.log(form)
      await delChapterInfo(form.id)
      ElMessage.success('删除成功')
      emit('refresh')
      handleCancel()
    } catch (error) {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  })
}

// 取消操作
const handleCancel = () => {
  formRef.value?.resetFields()
  emit('cancel')
}
</script>

<style scoped>
.add-chapter {
  padding: 20px;
}
.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
.button-group {
  margin-top: 20px;
  text-align: center;
}
</style>
